<template>
  <div>
    <BasicModal v-bind="$attrs" @register="register" :title="displayModuleTitle" width="1000px">
      <a-descriptions
        :column="6"
        :title="hazardInfo.title"
        bordered
        size="middle"
        :labelStyle="{ width: '150px' }"
      >
        <a-descriptions-item label="辨识日期" :span="2">{{
          hazardInfo.intm?.split(' ')[0] ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="辨识人" :span="2">{{
          hazardInfo.username ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="辨识结果" :span="2"
          ><a-tag
            v-if="hazardInfo.identificationresult !== null"
            :color="
              identifyOptions.filter((item) => item.value == hazardInfo.identificationresult)[0]
                ?.color
            "
          >
            {{
              identifyOptions.filter((item) => item.value == hazardInfo.identificationresult)[0]
                ?.text
            }}</a-tag
          >
          <span v-else>-</span></a-descriptions-item
        >

        <a-descriptions-item label="确认时间" :span="2">{{
          hazardInfo.confirmtm?.split(' ')[0] ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="确认人" :span="2">{{
          hazardInfo.confirmusername ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="确认结果" :span="2"
          ><a-tag
            v-if="hazardInfo.confirmresult !== null"
            :color="
              identifyOptions.filter((item) => item.value == hazardInfo.confirmresult)[0]?.color
            "
          >
            {{
              identifyOptions.filter((item) => item.value == hazardInfo.confirmresult)[0]?.text
            }}</a-tag
          >
          <span v-else>-</span>
          <a-button
            type="link"
            size="small"
            v-if="hazardInfo.hazardid && hazardInfo.confirmresult"
            @click="onViewHazardLogButtonClick"
            >查看</a-button
          >
        </a-descriptions-item>
        <a-descriptions-item label="单元" :span="3">{{ hazardInfo?.unitname }}</a-descriptions-item>
        <a-descriptions-item label="具体部位" :span="3">{{
          hazardInfo.position ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="一般/重大" :span="6"
          ><a-tag :color="hazardInfo.ismajor ? '#cd201f' : '#3b5999'">{{
            hazardInfo.ismajor ? '重大' : '一般'
          }}</a-tag></a-descriptions-item
        >
        <a-descriptions-item label="类别" :span="2">{{
          hazardInfo?.categoryname
        }}</a-descriptions-item>
        <a-descriptions-item label="项目" :span="2">{{
          hazardInfo?.projectname
        }}</a-descriptions-item>
        <a-descriptions-item label="危险源" :span="2"
          >{{ hazardInfo.itemname }}
        </a-descriptions-item>
        <a-descriptions-item label="事故诱因" :span="6">
          {{ hazardInfo?.couse ?? '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="可能导致的后果" :span="6">
          {{ hazardInfo?.maycouseharm ?? '-' }}
        </a-descriptions-item>

        <a-descriptions-item label="描述" :span="6">
          {{ hazardInfo?.description ?? '-' }}
        </a-descriptions-item>
      </a-descriptions>
      <a-divider v-if="hazardInfo.attachment && mode != 'confirm'">辨识记录附件信息</a-divider>
      <div class="flex-row" v-if="mode != 'confirm'">
        <a-carousel
          arrows
          :autoplay="true"
          :dots="true"
          effect="fade"
          style="width: 400px; height: 220px"
          dot-position="top"
          v-if="hazardInfo.attachment"
        >
          <template #prevArrow>
            <div class="custom-slick-arrow z-0" style="left: 10px">
              <LeftOutlined />
            </div>
          </template>
          <template #nextArrow>
            <div class="custom-slick-arrow" style="right: 10px">
              <RightOutlined />
            </div>
          </template>
          <div
            v-for="(item, index) in hazardInfo.attachment.filter(
              (item) => item.type == 'png' || item.type == 'jpg',
            )"
          >
            <div class="relativdive">
              <img class="swipper-img" :src="item.url" />
              <h3 class="absolute z-10 left-2 inset-y-26 h-15">{{ item.title }}</h3>
              <div
                style="background-color: #aeaeae; opacity: 0.4"
                class="absolute z-10 inset-x-0.2 inset-y-52 h-8"
              ></div>
            </div>
          </div>
        </a-carousel>
        <a-list
          class="Alist"
          item-layout="horizontal"
          v-if="hazardInfo.attachment"
          :data-source="
            hazardInfo.attachment.filter((item) => item.type !== 'png' && item.type !== 'jpg')
          "
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <template #actions>
                <a @click="downloadFile(item)">下载</a>
              </template>
              <a-list-item-meta>
                <template #title>
                  <span>{{ item.title }}</span>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </div>
      <a-divider v-if="mode == 'confirm'">辨识确认</a-divider>
      <a-alert
        v-if="mode == 'confirm'"
        :message="tooltip"
        type="info"
        v-show="tooltip"
        show-icon
        style="margin-bottom: 10px"
      />
      <BasicForm @register="registerForm" v-if="mode == 'confirm'"></BasicForm>
      <template #footer>
        <div v-if="mode == 'confirm'">
          <a-button @click="closeModal">取消</a-button>
          <a-button type="primary" @click="onOkButtonClick">确认</a-button>
        </div>
      </template>
    </BasicModal>
    <HazardInfo @register="registerLogsModal" />
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted, ref, unref } from 'vue';
  import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useDrawer } from '/@/components/Drawer';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getOneIdentifyRecord } from '/@/api/ehs/hazard';
  import { confirmIdentifyFormSchema } from './hazard.data';
  import { confirmIdentifyRecord, queryHazardListByUnit } from '/@/api/ehs/hazard';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getFileApi } from '/@/api/platform/file';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import HazardInfo from './HazardInfo.vue';
  const { createMessage, createInfoModal, createErrorModal } = useMessage();
  export default defineComponent({
    components: { BasicModal, BasicForm, HazardInfo, LeftOutlined, RightOutlined },
    name: 'IdentifyConfirmModal',
    emits: ['register', 'success'],
    props: ['mode'],
    setup(props, { emit }) {
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: confirmIdentifyFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      const qrRef = ref<Nullable<QrCodeActionType>>(null);
      const { uploadUrl } = useGlobSetting();
      const identifyOptions = ref([]);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref();
      const hazardid = ref();
      const unitid = ref();
      const hazardInfo = ref({});
      const tooltip = ref('');
      const [registerLogsModal, { openDrawer: openLogsDrawer }] = useDrawer();
      const [register, { closeModal }] = useModalInner((data) => {
        resetFields();
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
            hazardid.value = unrefData.hazardid;
            unitid.value = unrefData.unitid;
            getOneIdentifyRecord(dataId.value).then((res) => {
              hazardInfo.value = res;
              if (res.attachment) {
                hazardInfo.value.attachment = returnAttachment(res.attachment);
                console.log('attachment', hazardInfo.value.attachment);
              }
            });
            if (props.mode == 'confirm') {
              queryHazardListByUnit({
                unitid: data.unitid,
                categorycode: data.categorycode,
                projectcode: data.projectcode,
                itemcode: data.itemcode,
              }).then((res) => {
                // 如通过查询指定单元的危险源集合为空，自动选择新危险源，并使用文字提示：单元的危险源台账暂不存在任何记录；
                if (!res || res.length < 1) {
                  setFieldsValue({
                    type: 0,
                    confirmresult: unrefData.confirmresult >= 0 ? unrefData.confirmresult : 0,
                  });
                  tooltip.value = '单元的危险源台账暂不存在任何记录';
                } else {
                  // 如通过查询指定单元的危险源集合不为空，默认选择第1条危险源，并使用文字提示：
                  // 单元的危险源台账中已有记录，如本次辨识为新危险源请选择“新危险源”；
                  setFieldsValue({
                    type: 1,
                    hazardid: hazardid.value ?? res[0]?.hazardid,
                    confirmresult: unrefData.confirmresult >= 0 ? unrefData.confirmresult : 0,
                  });
                  tooltip.value =
                    '单元的危险源台账中已有记录，如本次辨识为新危险源请选择“新危险源”';
                }
                updateSchema({
                  field: 'hazardid',
                  componentProps: {
                    options: res?.map((item) => {
                      return {
                        label: item.hazardname,
                        value: item.hazardid,
                      };
                    }),
                  },
                });
              });
            }
          }
        }
      });

      /**
       * 单元二维码下载
       */
      function download() {
        const qrEl = unref(qrRef);
        if (!qrEl) return;
        qrEl.download(hazardInfo.value?.hazardname);
      }

      /**
       * 下载附件
       */
      function downloadFile(item) {
        downloadByUrl({ url: item.url, fileName: item.name });
      }

      /**
       * 返回JSON格式的附件信息数组
       */
      function returnAttachment(attachment) {
        return JSON.parse(attachment).map((item) => {
          let url = uploadUrl + getFileApi + item.id;
          let title = item.name + '.' + item.type;
          return {
            ...item,
            title,
            url,
          };
        });
      }

      function onViewHazardLogButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源信息',
          operateType: OperationTypeEnum.VIEW,
          dataId: hazardInfo.value.hazardid,
        };
        openLogsDrawer(true, propsData);
      }

      async function onOkButtonClick() {
        let values = await validate();
        confirmIdentifyRecord({
          ...values,
          hazardid: values.type == 0 ? '' : values.hazardid,
          identifyid: dataId.value,
        }).then((res) => {
          if (res.success) {
            createInfoModal({ title: '提示', content: res.msg });
            closeModal();
            emit('success');
          } else {
            createErrorModal({ title: '提示', content: res.msg });
          }
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      onMounted(() => {
        queryEnumOptions('EhsHazardIndentificationResultTypeEnum').then((res2) => {
          // console.log('option res', res);
          if (res2 != undefined && res2 != null && res2.length > 0x0) {
            const identifyOp = res2[0].options.map((option) => {
              return {
                value: option.key,
                text: option.value,
                color: option.attribute?.split('"')[3],
              };
            });
            identifyOptions.value = identifyOp;
          }
        });
      });

      return {
        qrRef,
        tooltip,
        hazardInfo,
        download,
        downloadFile,
        identifyOptions,
        register,
        registerLogsModal,
        registerForm,
        closeModal,
        displayModuleTitle,
        onOkButtonClick,
        onViewHazardLogButtonClick,
      };
    },
  });
</script>
<style lang="less" scoped>
  /* 轮播图的图片的高度为轮播区域高度(20rem)减去上下的边距(合计1rem) */
  @swipper-img-height: 20rem-5rem;

  .ant-carousel :deep(.slick-slide) {
    height: @swipper-img-height;
    line-height: @swipper-img-height;
    background: #dcdcdc;
    overflow: hidden;
  }

  .ant-carousel :deep(.slick-arrow.custom-slick-arrow) {
    width: 25px;
    height: 25px;
    font-size: 25px;
    color: #fff;
    opacity: 0.5;
    z-index: 1;
  }
  .ant-carousel :deep(.custom-slick-arrow:before) {
    display: none;
  }
  .ant-carousel :deep(.custom-slick-arrow:hover) {
    opacity: 0.8;
  }

  .ant-carousel :deep(.slick-slide h3) {
    color: #ffffff;
  }

  //轮播图缩放样式
  .relative {
    width: 100%;
    height: 250px;
  }
  .relativdive {
    width: 100%;
    height: 250px;
  }
  .swipper-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .flex-row {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }
  .Alist {
    flex: 1;
    margin-left: 10px;
    padding: 0 10px;
    border-left: 1px solid rgb(247, 247, 247);
  }
</style>
